package com.njxzc.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.entity.CartEntity;
import com.ie.entity.GoodsEntity;
import com.ie.entity.OrderdetailEntity;
import com.ie.entity.OrdersEntity;
import com.ie.mapper.admin.OrdersMapper;
import com.ie.service.before.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@SuppressWarnings("all")
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersEntity> implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderdetailService orderdetailService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartService cartService;

    /**
     * @classname: OrdersServiceImpl
     * @Author: royxu
     * @Description: 查询所有订单，或者根据订单编号查询
     * @Date: 2025/5/21  22:37
     * @Param: [ordersEntity]
     * @version: 1.0
     **/
    @Override
    public ResponseResult<Map<String, Object>> getAllOrders(OrdersEntity ordersEntity) {
        IPage<OrdersEntity> iPage = new Page<>(ordersEntity.getCurrentPage(), 5);
        // 构造条件，此处也可以使用lambdaquerywrapper来实现
        // QueryWrapper<OrdersEntity> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<OrdersEntity> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        Integer id = ordersEntity.getId();
        if (id != null && id > 0)
            LambdaQueryWrapper.eq(OrdersEntity::getId, id);
        // 分页查询（商品管理进来时初始查询及条件查询）
        IPage<OrdersEntity> page = page(iPage, LambdaQueryWrapper);
        Map<String, Object> myres = new HashMap<>();
        myres.put("allOrders", page.getRecords());
        myres.put("totalPage", page.getPages());
        return ResponseResult.getSuccessResult(myres);
    }

    /**
     * @Description: 查询订单详情
     * @Author: royxu
     * @Date: 2025/5/21  22:40
     * @Param: [ordersEntity]
     * @version: 1.0
     * @Return: com.ie.common.http.ResponseResult<java.util.List < java.util.Map < java.lang.String, java.lang.Object>>>
     **/
    @Override
    public ResponseResult<List<Map<String, Object>>> getOrdersDetail(OrdersEntity ordersEntity) {
        return ResponseResult.getSuccessResult(ordersMapper.getOrdersDetail(ordersEntity));
    }

    /**
     * @Description: 用户查询订单
     * @Author: royxu
     * @Date: 2025/5/21  22:38
     * @Param: [ordersEntity]
     * @version: 1.0
     * @Return: com.ie.common.http.ResponseResult<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    @Override
    public ResponseResult<Map<String, Object>> getOrdersByUid(OrdersEntity ordersEntity) {
        // 5为每页大小
        // https://blog.csdn.net/u010055960/article/details/141229482
        IPage<OrdersEntity> iPage = new Page<>(ordersEntity.getCurrentPage(), 5);
        LambdaQueryWrapper<OrdersEntity> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper.eq(OrdersEntity::getBusertableId, ordersEntity.getBusertableId()).orderByAsc(OrdersEntity::getStatus);
        // 分页查询（商品管理进来时初始查询及条件查询）
        // SELECT COUNT(*) AS total FROM orderbasetable WHERE (busertable_id = ?)
        IPage<OrdersEntity> page = page(iPage, LambdaQueryWrapper);
        Map<String, Object> myres = new HashMap<>();
        myres.put("ordersByUid", page.getRecords());
        myres.put("totalPage", page.getPages());
        return ResponseResult.getSuccessResult(myres);
    }

    @Override
    public ResponseResult<List<OrdersEntity>> selectOrderByMonth(OrdersEntity ordersEntity) {
        // 默认查询所有订单
        if (ordersEntity.getStartDate().length() == 0)
            ordersEntity.setStartDate("1900-01");
        if (ordersEntity.getEndDate().length() == 0)
            ordersEntity.setEndDate("9000-12");
        List<OrdersEntity> ordersEntityList = query()
                // 指定了查询结果中需要返回的字段。这里选择了订单金额的总和（sum(amount)）并命名为totalamount，
                // 以及订单日期格式化为YYYY-MM的月份（date_format(orderdate,'%Y-%m')）并命名为months。
                .select("sum(amount) totalamount", "date_format(orderdate,'%Y-%m') months")
                .eq("status", 1)
                // 选择在指定日期范围内的订单，日期范围由ordersEntity.getStartDate()和ordersEntity.getEndDate()提供
                .between("date_format(orderdate,'%Y-%m')", ordersEntity.getStartDate(), ordersEntity.getEndDate())
                .groupBy("months")
                .orderByAsc("months")
                .list();
        return ResponseResult.getSuccessResult(ordersEntityList);
    }

    @Override
    public ResponseResult<List<Map<String, Object>>> selectOrderByType() {
        List<Map<String, Object>> ls = ordersMapper.selectOrderByType();
        System.out.println(ls);
        return ResponseResult.getSuccessResult(ordersMapper.selectOrderByType());
    }

    @Override
    @Transactional // 事务管理，submitOrder方法是原子性的
    public ResponseResult<OrdersEntity> submitOrder(OrdersEntity ordersEntity) {
        ordersEntity.setStatus(0);
        ordersEntity.setOrderdate(new Date());
        // 生成订单
        save(ordersEntity);
        // 生成订单详情
        /**
         获取订单中的商品ID列表bgid和购买数量列表bshoppingnum。
         创建两个列表bods和ges，分别用于存储订单详情和商品实体。
         遍历商品ID列表，为每个商品创建一个订单详情实体OrderdetailEntity和一个商品实体GoodsEntity。
         设置订单详情实体的订单ID、商品ID和购买数量。
         更新商品实体的库存数量，并减少相应数量。
         将订单详情实体和商品实体添加到对应的列表中。
         */
        List<Integer> bgid = ordersEntity.getBgid();
        List<Integer> bshoppingnum = ordersEntity.getBshoppingnum();
        List<OrderdetailEntity> bods = new ArrayList<OrderdetailEntity>();
        List<GoodsEntity> ges = new ArrayList<GoodsEntity>();
        // 根据订单表完成订单详细表
        for (int i = 0; i < bgid.size(); i++) {
            OrderdetailEntity ot = new OrderdetailEntity();
            GoodsEntity ge = new GoodsEntity();
            ot.setOrderbasetableId(ordersEntity.getId());
            ot.setGoodstableId(bgid.get(i));
            ot.setShoppingnum(bshoppingnum.get(i));
            bods.add(ot);
            ge.setId(bgid.get(i));
            // 减少库存
            ge.setGstore(goodsService.getById(bgid.get(i)).getGstore() - bshoppingnum.get(i));
            ges.add(ge);
        }
        orderdetailService.saveBatch(bods);
        // 批量更新库存
        goodsService.updateBatchById(ges);
        // 清空购物车
        CartEntity cartEntity = new CartEntity();
        cartEntity.setBusertableId(ordersEntity.getBusertableId());
        cartService.clearCart(cartEntity);
        return ResponseResult.getSuccessResult(ordersEntity);
    }

    /**
     * @Description:
     * @Author: royxu
     * @Date: 2025/5/29  23:02
     * @Param: [ordersEntity]
     * @version: 1.0
     * @Return: com.ie.common.http.ResponseResult<com.ie.entity.OrdersEntity>
     **/
    @Override
    public ResponseResult<OrdersEntity> goSubmitOrder(OrdersEntity ordersEntity) {
        ordersEntity.setStatus(0);
        ordersEntity.setOrderdate(new Date());
        // 生成订单
        save(ordersEntity);
        // 生成订单详情
        List<Integer> bgid = ordersEntity.getBgid();
        List<Integer> bshoppingnum = ordersEntity.getBshoppingnum();
        List<OrderdetailEntity> bods = new ArrayList<OrderdetailEntity>();
        List<GoodsEntity> ges = new ArrayList<GoodsEntity>();
        for (int i = 0; i < bgid.size(); i++) {
            OrderdetailEntity ot = new OrderdetailEntity();
            GoodsEntity ge = new GoodsEntity();
            ot.setOrderbasetableId(ordersEntity.getId());
            ot.setGoodstableId(bgid.get(i));
            ot.setShoppingnum(bshoppingnum.get(i));
            bods.add(ot);
            ge.setId(bgid.get(i));
            // 减少库存
            ge.setGstore(goodsService.getById(bgid.get(i)).getGstore() - bshoppingnum.get(i));

            ges.add(ge);
        }
        orderdetailService.saveBatch(bods);
        // 批量更新库存
        goodsService.updateBatchById(ges);

        // 直接购买未调用购物车模块，无需购物车操作
        // CartEntity cartEntity = new CartEntity();
        // cartEntity.setBusertableId(ordersEntity.getBusertableId());
        // cartService.clearCart(cartEntity);
        return ResponseResult.getSuccessResult(ordersEntity);

    }

    @Override
    public ResponseResult<Map<String, String>> goPay(OrdersEntity ordersEntity) {
        // 调用支付宝或者微信支付模块完成支付
        // https://blog.csdn.net/weixin_74318097/article/details/135383241
        // https://blog.csdn.net/hhb442/article/details/123304287
        // https://blog.csdn.net/gh_xiaohe/article/details/128162400
        // 支付成功后，修改订单状态0-->1
        ordersEntity.setStatus(1);
        if (updateById(ordersEntity)) {
            return ResponseResult.getMessageResult(null, "A001");
        }
        return ResponseResult.getMessageResult(null, "A002");
    }

    @Override
    public ResponseResult<OrdersEntity> cancelOrder(OrdersEntity ordersEntity) {
        return null;
    }
}
